<?php
namespace Modules\Book\Library;

class Toc
{
    protected static $toc = array();
    protected static $tocIndex = 0;

    //文章目录
    public static function toc(string $body)
    {
        $body = preg_replace_callback('/<h([2-5])>([^<]*).*?<\/h[2-5]>/i', 'self::tocReplace', $body);
        return [
            'body' => $body,
            'toc' => self::$toc
        ];
    }

    public static function tocReplace($matches)
    {
        self::$tocIndex++;
        $matches[1] = (int)$matches[1];
        self::$toc[self::$tocIndex] = '<a class="scroll-to margin-' . $matches[1] . '" href="#toc' . self::$tocIndex . '">' . $matches[2] . '</a>';
        return '<h' . $matches[1] . '>' . $matches[2] . '<a class="toc toc-' . self::$tocIndex . '" id="toc' . self::$tocIndex . '"></a></h' . $matches[1] . '>';
    }
}